package cs.uns.edu.ar.aygps.service.data;

import java.awt.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;

import org.dom4j.Document;
import org.dom4j.Element;

import com.toedter.calendar.JDateChooser;

import cs.uns.edu.ar.aygps.model.exception.AyGPSException;

public class ServiceDataHelper {

	public static Map getServiceData(String configFilePath, Component[] components) throws AyGPSException {
		XMLHelper helper = new XMLHelper();
		Document doc = helper.parseStream(configFilePath);	
		Map comp = getComponentsAsMap(components);
		return generateServiceData(doc,comp);
	}

	private static Map getComponentsAsMap(Component[] components) {
		HashMap<String,Object> m = new HashMap<String, Object>();
		for (int i=0;i<components.length;i++){
			Component c = components[i];
			if (c instanceof JTextField) {
				if (!"".equals(((JTextField) c).getText())){
					m.put(c.getName(),((JTextField) c).getText());	
				}				
			}
			if (c instanceof JCheckBox){
				m.put(c.getName(), new Boolean(((JCheckBox) c).isSelected()));
			}
			if (c instanceof JComboBox){
				m.put(c.getName(), ((JComboBox)c).getSelectedItem().toString());
			}
			if (c instanceof JDateChooser){
				m.put(c.getName(), ((JDateChooser)c).getDate());
			}
		}
		return m;
	}

	private static Map generateServiceData(Document doc, Map components ) {
		HashMap<String,Object> serviceData = new HashMap<String, Object>();
		
		Element root = doc.getRootElement();
		final String service = root.attributeValue("service");
		
		Iterator ti = root.elementIterator("dataItem");
		while (ti.hasNext()) {
			Element node = (Element) ti.next();
			Element fieldElement = node.element("field");
			String key = fieldElement.getTextTrim();
			Element fieldTypeElement = node.element("fieldType");
			Object value = getValue(fieldTypeElement.getTextTrim(),components.get(key));
			if (value!=null){
				serviceData.put(key, value);
			}			
		}
		
		return serviceData;
	}

	private static Object getValue(String type, Object object) {		
		if ("java.lang.String".equals(type) || "java.lang.Boolean".equals(type)){
			return object;
		}
		if ("java.lang.Integer".equals(type)){
			if (object!=null)
				return Integer.parseInt((String)object);
		}
		if ("java.util.Date".equals(type)){
			return object;
		}		
		if ("java.lang.Double".equals(type)){
			if (object!=null){
				return Double.parseDouble((String)object);
			}
		}
		return null;
	}
		

}
